const countToDate = new Date().setHours(new Date().getHours() + 24); // 程序执行时的时间点

setInterval(() => {
  const currentDate = new Date();
  const timeBetweenDates = Math.ceil((countToDate - currentDate) / 1000); // 计算时间差
  flipAllCards(timeBetweenDates);
}, 250);

/**
 * 对所有单个倒计时器卡片进行数值设置
 * @param {Number} time 当前倒计时的时间（毫秒值）
 */
function flipAllCards(time) {
  const seconds = time % 60;
  const minutes = Math.floor(time / 60) % 60;
  const hours = Math.floor(time / 3600);

  flip(document.querySelector("[data-hours-tens]"), Math.floor(hours / 10));
  flip(document.querySelector("[data-hours-ones]"), hours % 10);
  flip(document.querySelector("[data-minutes-tens]"), Math.floor(minutes / 10));
  flip(document.querySelector("[data-minutes-ones]"), minutes % 10);
  flip(document.querySelector("[data-seconds-tens]"), Math.floor(seconds / 10));
  flip(document.querySelector("[data-seconds-ones]"), seconds % 10);
}

/**
 * 单个翻牌动画
 * @param {HTMLElement} flipCard 单个倒计时器卡片容器
 * @param {Number} newNumber 下一次翻牌的新数值
 * @returns void
 */
function flip(flipCard, newNumber) {
  const topHalf = flipCard.querySelector(".top");
  const bottomHalf = flipCard.querySelector(".bottom");
  const startNumber = parseInt(topHalf.textContent);

  if (newNumber === startNumber) return;

  const topFlip = document.createElement("div");
  topFlip.classList.add("top_flip");
  const bottomFlip = document.createElement("div");
  bottomFlip.classList.add("bottom_flip");

  top.textContent = startNumber;
  bottomHalf.textContent = startNumber;
  topFlip.textContent = startNumber;
  bottomFlip.textContent = newNumber;

  topFlip.addEventListener("animationstart", (e) => {
    topHalf.textContent = newNumber;
  });

  topFlip.addEventListener("animationend", (e) => {
    topFlip.remove();
  });

  bottomFlip.addEventListener("animationend", (e) => {
    bottomHalf.textContent = newNumber;
    bottomFlip.remove();
  });

  flipCard.append(topFlip, bottomFlip);
}
